var express = require('express')
var router = express.Router()
/* 导入jwt香相关文件 */
// 1.用于生成jwt字符串
var jwt = require('jsonwebtoken')
// 2.将jwt字符串解析还原成JSON对象
// const expressJWT = require('express-jwt')
const config = require('../token/config')
// 导入自己封装的数据库操作模块
const exec = require('../db')
const { isValidToken } = require('../token')
// 定义秘钥
const secret = 'register-rule'
//导入调试的标记
const { debug } = require('../config')
/* 获取所有用户 */
router.get('/user', async (req, res) => {
  const { page = 1, num = 5 } = req.query
  let sql = `select count(*) as total from gg_user`
  const { total } = (await exec(sql))[0]
  let offset = (page - 1) * num
  sql = `select * from gg_user order by id limit ${offset},${num}`
  try {
    let data = await exec(sql)
    res.send({
      code: 0,
      msg: '获取用户成功',
      result: {
        total,
        data,
      },
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '获取用户失败',
      result: debug ? err : '',
    })
  }
})
/* 新增用户 */ 1
router.post('/user', async (req, res) => {
  console.log(req.body)
  let { user_name, user_password, user_type, user_truname, user_phone } =
    req.body
  let sql = `insert into gg_user (user_name,user_password,user_type,user_truname,user_phone ) values ('${user_name}', '${user_password}','${user_type}','${user_truname}','${user_phone}' )`
  try {
    const data = await exec(sql)
    // console.log(data)
    res.send({
      code: 0,
      msg: '新增用户成功',
      result: data,
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '新增用户失败',
      result: debug ? err : '',
    })
  }
})
/* 根据id获取 */
router.get('/user/:id', async (req, res) => {
  let { id } = req.params
  let sql = `select *  from gg_user where id = ${id}`
  try {
    let data = await exec(sql)
    res.send({
      code: 0,
      msg: '获取用户成功',
      result: data,
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '获取用户失败',
      result: debug ? err : '',
    })
  }
})
/* 根据用户模糊查询 */
router.post('/user/username', async (req, res) => {
  const { page = 1, size = 4, user_name } = req.query
  // req.query是请求参数
  //?user_name=admin
  // 获取总数
  let sql = `select count(*) as total  from gg_user  where user_name like'%${user_name}%'`
  const obj = await exec(sql)
  let offset = (page - 1) * size
  // 操作数据库
  sql = `select * from gg_user where user_name like'%${user_name}%' order by id asc  limit ${offset}, ${size} `
  try {
    const data = await exec(sql)
    res.send({
      code: 0,
      message: '获取用户成功',
      result: data,
    })
  } catch (err) {
    res.send({
      code: 1,
      message: '获取用户失败',
      result: debug ? err : '',
    })
  }
})
/* 修改用户 */
router.put('/user/:id', async (req, res) => {
  let { id } = req.params
  console.log(req.body)
  let { user_name, user_password, user_type, user_status, user_phone } =
    req.body
  let sql = `update gg_user set user_name='${user_name}',
                                 user_password='${user_password}',
                                 user_type='${user_type}',
                                 user_status='${user_status}',
                                 user_phone='${user_phone}'
              where id=${id} `
  try {
    let data = await exec(sql)
    res.send({
      code: 0,
      msg: '修改用户成功',
      result: data,
    })
  } catch (err) {
    res.send({
      code: 0,
      msg: '修改用户失败',
      result: debug ? err : '',
    })
  }
})
/* 删除用户 */
router.delete('/user/:id', async (req, res) => {
  let { id } = req.params
  let sql = `delete from gg_user where id=${id}`
  try {
    await exec(sql)
    res.send({
      code: 0,
      msg: '删除成功',
      result: '',
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '删除失败',
      result: debug ? err : '',
    })
  }
})
/* 仿写模板 */
// router.get('/user', async (req, res) => {
/*
    let { id } = req.params   // 获取:后面的参数 /:id
    const { pages, num } = req.query   // 获取?后面的参数 /messages?pages=1&num=5
    let { username, password } = req.body   // 获取请求体参数 {}
  */
//   let sql = `select * from gg_user`

//   try {
//     let data = await exec(sql)
//     res.send({
//       code: 0,
//       msg: '成功!',
//       result: data,
//     })
//   } catch (err) {
//     res.send({
//       code: 1,
//       msg: '失败!',
//       result: debug ? err : '',
//     })
//   }
// })

/* 登录 */
router.post('/user/login', async (req, res) => {
  const { user_name, user_password } = req.body
  // 当输入用户名与密码格式不对
  if (!user_name && !user_password) {
    return res.send({
      code: 1,
      msg: '用户或密码输入不正确',
      result: '用户或密码输入不正确',
    })
  }
  // 当输入用户名与密码格式正确时
  let sql = `select * from gg_user`
  // 获取后端所有用户信息
  const resData = await exec(sql)
  // console.log(resData)
  // 遍历后端的用户名，赋值给变量user
  let user = resData.map((item) => item.user_name)
  // 如果user里不包括输入的用户名，返回提示信息
  if (!user.includes(user_name)) {
    return res.send('该用户不存在')
  }
  // 如果user里有输入的用户名，继续执行以下代码
  if (user.includes(user_name)) {
    // 筛选出数据库中用户名与输入框用户名相等的用户的所有信息
    let sql2 = `select * from gg_user where user_name='${user_name}'`
    // 将某个用户信息赋值给dataByName
    const dataByName = await exec(sql2)
    // 再从某个用户的信息中筛选出他的密码
    let sql1 = `select user_password from gg_user where user_name='${user_name}'`
    // 将密码赋值给psw
    const psw = await exec(sql1)
    // console.log(psw)
    // 将这个用户的登录状态筛选出来
    let sql3 = `select user_status from gg_user where user_name='${user_name}'`
    // 将他的id也筛选出来
    let sql4 = `select id from gg_user where user_name='${user_name}'`
    // 拿到类型类型
    let sql5 = `select user_type from gg_user where user_name='${user_name}'`
    // 拿到用户状态
    let sql6 = `select user_status from gg_user where user_name='${user_name}'`
    // 将登录状态和用户id分别给sta和staAdmin
    const sta = await exec(sql3)
    // console.log(sta)
    const staAdmin = await exec(sql4)
    // console.log(staAdmin)
    const staType = await exec(sql5)
    const status = await exec(sql6)
    // console.log(staType)
    // const { user_type } = staType.user_type
    // console.log(sta[0].user_status) //拿到状态值判断是否被禁用
    // console.log(staAdmin[0].user_id)
    // 如果用户密码相等并且登录状态是未登录，就让它登录成功
    // if (user_password == psw[0].user_password && sta[0].user_status == 0) {
    if (user_password == psw[0].user_password) {
      // 不要把密码加密到token字符串中
      let token = jwt.sign({ user_name }, config.token.secretKey, {
        expiresIn: '24h' /* 自带的参数 */,
      })
      return res.send({
        code: 0,
        message: '登录成功',
        result: {
          id: staAdmin[0].id,
          user_name,
          user_type: staType[0].user_type,
          user_status: status[0].user_status,
          token,
        },
      })
    } else {
      return res.send({
        code: 1,
        msg: '密码错误或你已被禁用',
      })
    }
  }
})
/* 注册 */
router.post('/user/register', async (req, res) => {
  // 解构数据
  const { user_name, user_password, user_truname, user_phone } = req.body
  // console.log(req.body)
  if (!user_name || !user_password || !user_truname || !user_phone) {
    return res.send({
      code: 1,
      msg: '输入信息有误',
      result: '用户信息不能为空',
    })
  }
  // 条件查询
  let sql = `select * from gg_user`
  const resData = await exec(sql)
  console.log(resData)
  // 遍历数据库的用户名
  let user = resData.map((item) => item.user_name)
  // 如果数据库里有这个用户名，代码结束并返回该信息
  if (user.includes(user_name)) {
    return res.send('该用户已存在')
  }
  // 数据库没有这个用户名,继续注册
  if (!user.includes(user_name)) {
    let sql = `insert into gg_user (user_name,user_password, user_truname,user_phone )  values  ('${user_name}', '${user_password}','${user_truname}','${user_phone}')`
    try {
      const data = await exec(sql)
      console.log(data)
      res.send({
        code: 0,
        message: '注册用户成功',
        result: data,
      })
    } catch (err) {
      res.send({
        code: 'err',
        message: '注册用户失败',
        result: debug ? err : '',
      })
    }
  }
})
//验证token
router.post('/user/vertify', isValidToken)
module.exports = router
